import Footer from '@/components/Footer';
import {LockOutlined, UserOutlined,} from '@ant-design/icons';
import {LoginForm, ProFormCheckbox, ProFormText,} from '@ant-design/pro-components';
import {message, Space, Tabs} from 'antd';
import React, {useState} from 'react';
import {history, useModel} from 'umi';
import {GITEE_LINK} from "@/constants";
import styles from './index.less';
import {adminLoginUsingPOST} from "@/services/ant-design-pro/denglujiekou";
import {setToken} from "@/plugins/localstorage";


const Login: React.FC = () => {
  const [type, setType] = useState<string>('account');
  const {initialState, setInitialState} = useModel('@@initialState');
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };

  const handleSubmit = async (values: API.LoginFormDTO) => {
    try {
      // 登录
      const user = await adminLoginUsingPOST({
        ...values,
      });
      const userValue = user.data;
      console.log('登录者信息', userValue)
      // setAdmin(userValue);

      // @ts-ignore
      setToken(userValue.token);
      if (userValue) {
        const defaultLoginSuccessMessage = '登录成功！';
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();

        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;

        const {query} = history.location;
        const {redirect} = query as {
          redirect: string;
        };
        history.push(redirect || '/');
        return;
      }

    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      message.error(defaultLoginFailureMessage);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          logo={<img alt="logo" src='/logo.svg'/>}
          title="绿源味道"
          subTitle={<a href={GITEE_LINK} target={"_blank"} rel="noreferrer"> [绿源味道] 是全球最具影响力的 农场品
            追溯平台 </a>}
          initialValues={{
            autoLogin: true,
          }}

          onFinish={async (values) => {
            await handleSubmit(values as API.LoginFormDTO);
          }}
        >
          <Tabs activeKey={type} onChange={setType}>
            <Tabs.TabPane key="account" tab={'账号密码登录'}/>
          </Tabs>


          {type === 'account' && (
            <>
              <ProFormText
                name="account"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon}/>,
                }}
                placeholder={'请输入账号'}
                rules={[
                  {
                    required: true,
                    message: '账号是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon}/>,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                  {
                    min: 6,
                    type: "string",
                    message: '密码不少于6位！',
                  },
                ]}
              />
            </>
          )}

          <div
            style={{
              marginBottom: 24,
            }}
          >
            <Space>
              <ProFormCheckbox noStyle name="autoLogin">
                自动登录
              </ProFormCheckbox>


              {/*<a*/}
              {/*  style={{*/}
              {/*    float: 'right',*/}
              {/*  }}*/}
              {/*  href={'https://gitee.com/whxsw'}*/}
              {/*  target={"_blank"} rel="noreferrer"*/}
              {/*>*/}
              {/*  忘记密码?*/}
              {/*</a>*/}
            </Space>
          </div>
        </LoginForm>
      </div>
      <Footer/>
    </div>
  );
};
export default Login;
